package com.zj.transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbcTransaction implements Transaction {
    //日志框架日后再研究
//    private static final Log log = LogFactory.getLog(JdbcTransaction.class);
    protected Connection connection;
    protected DataSource dataSource;
    protected TransactionIsolationLevel level;
    protected boolean autoCommit;

    public JdbcTransaction(Connection conn){
        this.connection=conn;
    }

    public JdbcTransaction(DataSource dataSource,TransactionIsolationLevel level,boolean autoCommit){
        this.dataSource=dataSource;
        this.level=level;
        this.autoCommit=autoCommit;
    }




    @Override
    public Connection getConnection() throws SQLException {
        if (this.connection == null) {
            this.openConnection();
        }
        return this.connection;
    }

    @Override
    public void commit() throws SQLException {
        if (this.connection != null && !this.connection.getAutoCommit()) {
            this.connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if (this.connection != null && !this.connection.getAutoCommit()) {
            this.connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if (this.connection != null) {
            this.resetAutoCommit();
            this.connection.close();
        }

    }

    @Override
    public Integer getTimeout() throws SQLException {
        return null;
    }

    protected void resetAutoCommit() {
        try {
            if (!this.connection.getAutoCommit()) {
                 this.connection.setAutoCommit(true);
            }
        } catch (SQLException var2) {
        }
    }

    protected void openConnection() throws SQLException {
        this.connection = this.dataSource.getConnection();
        if (this.level != null) {
            this.connection.setTransactionIsolation(this.level.getLevel());
        }
        if (this.connection.getAutoCommit() != this.autoCommit) {
            this.connection.setAutoCommit(this.autoCommit);
        }
    }
}
